import router from '@/router';
import { useUserStore } from '@/stores/modules/user';
import { showToast } from 'vant';

import axios from 'axios';

axios.defaults.baseURL = '/';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL
});
request.defaults.timeout = 10000;
// request.defaults.headers.common['Authorization'] = AUTH_TOKEN;

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    config.headers['Authorization'] = `Bearer ${userStore.userInfo.token || ''}`;

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 10000) {
      showToast(res.message);
      return Promise.reject(res);
    }

    return res.data;
  },
  (error) => {
    console.log(error);
    if (error.response.status === 401) {
      const userStore = useUserStore();
      userStore.deleteUserInfo();
      // router.push(`/login?returnUrl=${router.currentRoute.value.fullPath}`);
    }
    // error.response.data  黑马接口的响应   error.response.data.code 黑马的接口code
    return Promise.reject(error);
  }
);

export default request;
